<template>
  <Layout>
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 用户信息头部 -->
      <div class="bg-white rounded-lg shadow-md overflow-hidden mb-8">
        <!-- 封面背景 -->
        <div class="h-48 bg-gradient-to-r from-blue-400 to-purple-500"></div>

        <!-- 用户信息 -->
        <div class="relative px-6 pb-6">
          <div class="flex flex-col sm:flex-row sm:items-end sm:space-x-6">
            <!-- 头像 -->
            <div class="-mt-20 sm:-mt-24">
              <img
                :src="user.avatar || `https://ui-avatars.com/api/?name=${user.name}&size=128`"
                :alt="user.name"
                class="w-32 h-32 sm:w-40 sm:h-40 rounded-full ring-4 ring-white"
              />
            </div>

            <!-- 用户基本信息 -->
            <div class="mt-6 sm:mt-0 flex-1">
              <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
                <div>
                  <h1 class="text-2xl font-bold text-gray-900">{{ user.name }}</h1>
                  <p class="text-gray-500">@{{ user.username }}</p>
                </div>

                <!-- 操作按钮 -->
                <div class="mt-4 sm:mt-0 flex space-x-3">
                  <button
                    v-if="!isOwnProfile"
                    @click="toggleFollow"
                    class="px-4 py-2 rounded-md text-sm font-medium transition-colors"
                    :class="isFollowing ? 'bg-gray-200 hover:bg-gray-300 text-gray-800' : 'bg-blue-600 hover:bg-blue-700 text-white'"
                  >
                    {{ isFollowing ? '已关注' : '关注' }}
                  </button>
                  <Link
                    v-if="isOwnProfile"
                    href="/profile/edit"
                    class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm font-medium"
                  >
                    编辑资料
                  </Link>
                </div>
              </div>

              <!-- 用户简介 -->
              <p class="mt-4 text-gray-600">{{ user.bio || '这个人很懒，什么都没有留下~' }}</p>

              <!-- 用户详细信息 -->
              <div class="mt-4 flex flex-wrap gap-4 text-sm text-gray-500">
                <div v-if="user.location" class="flex items-center">
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path>
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path>
                  </svg>
                  {{ user.location }}
                </div>
                <div v-if="user.website" class="flex items-center">
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path>
                  </svg>
                  <a :href="user.website" target="_blank" class="hover:text-blue-600">{{ user.website }}</a>
                </div>
                <div v-if="user.occupation" class="flex items-center">
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 13.255A23.931 23.931 0 0112 15c-3.183 0-6.22-.62-9-1.745M16 6V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v2m4 6h.01M5 20h14a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                  </svg>
                  {{ user.occupation }}
                </div>
                <div class="flex items-center">
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                  </svg>
                  加入于 {{ formatDate(user.created_at) }}
                </div>
              </div>

              <!-- 统计数据 -->
              <div class="mt-6 flex space-x-6">
                <div class="text-center">
                  <div class="text-2xl font-bold text-gray-900">{{ stats.posts_count }}</div>
                  <div class="text-sm text-gray-500">文章</div>
                </div>
                <button @click="showFollowers = true" class="text-center hover:opacity-75">
                  <div class="text-2xl font-bold text-gray-900">{{ stats.followers_count }}</div>
                  <div class="text-sm text-gray-500">粉丝</div>
                </button>
                <button @click="showFollowing = true" class="text-center hover:opacity-75">
                  <div class="text-2xl font-bold text-gray-900">{{ stats.following_count }}</div>
                  <div class="text-sm text-gray-500">关注</div>
                </button>
                <div class="text-center">
                  <div class="text-2xl font-bold text-gray-900">{{ stats.likes_received }}</div>
                  <div class="text-sm text-gray-500">获赞</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 选项卡 -->
      <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="border-b">
          <nav class="flex -mb-px">
            <button
              v-for="tab in tabs"
              :key="tab.key"
              @click="activeTab = tab.key"
              class="px-6 py-3 border-b-2 font-medium text-sm transition-colors"
              :class="activeTab === tab.key
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
            >
              {{ tab.label }}
            </button>
          </nav>
        </div>

        <!-- 内容区域 -->
        <div class="p-6">
          <!-- 文章列表 -->
          <div v-if="activeTab === 'posts'">
            <div v-if="posts.length === 0" class="text-center py-8 text-gray-500">
              暂无发布的文章
            </div>
            <div v-else class="space-y-6">
              <article v-for="post in posts" :key="post.id" class="border-b pb-6 last:border-b-0">
                <h3 class="text-xl font-semibold mb-2">
                  <Link :href="`/posts/${post.slug}`" class="hover:text-blue-600">
                    {{ post.title }}
                  </Link>
                </h3>
                <p class="text-gray-600 mb-3">{{ post.excerpt }}</p>
                <div class="flex items-center justify-between text-sm text-gray-500">
                  <div class="flex items-center space-x-4">
                    <span>{{ formatDate(post.published_at) }}</span>
                    <span>{{ post.views_count }} 阅读</span>
                    <span>{{ post.likes_count }} 点赞</span>
                    <span>{{ post.comments_count }} 评论</span>
                  </div>
                  <div v-if="post.category" class="bg-gray-100 px-3 py-1 rounded-full">
                    {{ post.category.name }}
                  </div>
                </div>
              </article>
            </div>
          </div>

          <!-- 关于 -->
          <div v-if="activeTab === 'about'" class="prose max-w-none">
            <h3 class="text-lg font-semibold mb-4">关于我</h3>
            <div v-html="user.about_me || '<p class=\'text-gray-500\'>暂无详细介绍</p>'"></div>

            <div v-if="user.skills && user.skills.length > 0" class="mt-6">
              <h3 class="text-lg font-semibold mb-4">技能标签</h3>
              <div class="flex flex-wrap gap-2">
                <span
                  v-for="skill in user.skills"
                  :key="skill"
                  class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm"
                >
                  {{ skill }}
                </span>
              </div>
            </div>

            <div v-if="socialLinks.length > 0" class="mt-6">
              <h3 class="text-lg font-semibold mb-4">社交链接</h3>
              <div class="flex space-x-4">
                <a
                  v-for="link in socialLinks"
                  :key="link.platform"
                  :href="link.url"
                  target="_blank"
                  class="text-gray-600 hover:text-gray-900"
                  :title="link.platform"
                >
                  <component :is="getSocialIcon(link.platform)" class="w-6 h-6" />
                </a>
              </div>
            </div>
          </div>

          <!-- 动态 -->
          <div v-if="activeTab === 'activity'">
            <div v-if="activities.length === 0" class="text-center py-8 text-gray-500">
              暂无动态
            </div>
            <div v-else class="space-y-4">
              <div v-for="activity in activities" :key="activity.id" class="flex items-start space-x-3">
                <div class="flex-shrink-0 w-8 h-8 bg-gray-200 rounded-full flex items-center justify-center">
                  <svg class="w-4 h-4 text-gray-600" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                    <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd" />
                  </svg>
                </div>
                <div class="flex-1">
                  <p class="text-gray-900">
                    {{ activity.description }}
                  </p>
                  <p class="text-sm text-gray-500 mt-1">{{ formatDate(activity.created_at) }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 粉丝列表弹窗 -->
    <Modal v-model="showFollowers" title="粉丝列表">
      <div class="space-y-4">
        <div v-for="follower in followers" :key="follower.id" class="flex items-center justify-between">
          <div class="flex items-center space-x-3">
            <img
              :src="follower.avatar || `https://ui-avatars.com/api/?name=${follower.name}`"
              :alt="follower.name"
              class="w-10 h-10 rounded-full"
            />
            <div>
              <Link :href="`/profile/${follower.username}`" class="font-medium hover:text-blue-600">
                {{ follower.name }}
              </Link>
              <p class="text-sm text-gray-500">@{{ follower.username }}</p>
            </div>
          </div>
        </div>
      </div>
    </Modal>

    <!-- 关注列表弹窗 -->
    <Modal v-model="showFollowing" title="关注列表">
      <div class="space-y-4">
        <div v-for="following in followingList" :key="following.id" class="flex items-center justify-between">
          <div class="flex items-center space-x-3">
            <img
              :src="following.avatar || `https://ui-avatars.com/api/?name=${following.name}`"
              :alt="following.name"
              class="w-10 h-10 rounded-full"
            />
            <div>
              <Link :href="`/profile/${following.username}`" class="font-medium hover:text-blue-600">
                {{ following.name }}
              </Link>
              <p class="text-sm text-gray-500">@{{ following.username }}</p>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  </Layout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Link, usePage } from '@inertiajs/inertia-vue3'
import Layout from '@/Components/Layout.vue'
import Modal from '@/Components/Modal.vue'
import axios from 'axios'

const props = defineProps({
  user: Object,
  posts: Array,
  stats: Object,
  isFollowing: Boolean,
  isOwnProfile: Boolean,
  activities: Array
})

const page = usePage()
const activeTab = ref('posts')
const showFollowers = ref(false)
const showFollowing = ref(false)
const followers = ref([])
const followingList = ref([])
const isFollowing = ref(props.isFollowing)

const tabs = [
  { key: 'posts', label: '文章' },
  { key: 'about', label: '关于' },
  { key: 'activity', label: '动态' }
]

const socialLinks = computed(() => {
  const links = []
  if (props.user.github) links.push({ platform: 'GitHub', url: props.user.github })
  if (props.user.twitter) links.push({ platform: 'Twitter', url: props.user.twitter })
  if (props.user.linkedin) links.push({ platform: 'LinkedIn', url: props.user.linkedin })
  return links
})

const toggleFollow = async () => {
  try {
    const response = await axios.post(`/follow/${props.user.id}`)
    isFollowing.value = response.data.is_following
  } catch (error) {
    console.error('关注操作失败:', error)
  }
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`
}

const getSocialIcon = (platform) => {
  // 这里简化处理，实际项目中可以引入对应的图标组件
  return 'div'
}

onMounted(async () => {
  // 加载粉丝列表
  if (props.stats.followers_count > 0) {
    try {
      const response = await axios.get(`/api/users/${props.user.id}/followers`)
      followers.value = response.data
    } catch (error) {
      console.error('加载粉丝列表失败:', error)
    }
  }

  // 加载关注列表
  if (props.stats.following_count > 0) {
    try {
      const response = await axios.get(`/api/users/${props.user.id}/following`)
      followingList.value = response.data
    } catch (error) {
      console.error('加载关注列表失败:', error)
    }
  }
})
</script>